//
//  THJDianJiaVC.m
//  THJXHW
//
//  Created by 河南德艺 on 2018/9/12.
//  Copyright © 2018年 河南德艺. All rights reserved.
//

#import "THJDianJiaVC.h"
#import "THJDianJiaCell.h"
#import "SocketRocket.h"
#import "THJSelectView.h"
#import "THJDJSelectView.h"
#import "THJDianJiaInfoVC.h"
#import "THJFabuDianjiaVC.h"
#import "THJLoginVC.h"

@interface THJDianJiaVC ()<UITableViewDelegate,UITableViewDataSource,SRWebSocketDelegate,THJDJSelectViewDelegate,UIScrollViewDelegate>
{
    SRWebSocket * socket;
    NSMutableArray * areaArr;
    NSMutableArray * classArr;
    NSMutableArray * gongyingArr;
    UITableView * _tableview;
    
    
    NSString * send1;
    NSString * send2;
    NSString * send3;
    NSString * send4;
    NSInteger gongyingFlag;
    NSMutableArray * dataArr;
    NSString * classType;
    //发布按钮
    UIButton * btn;
}
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet UIButton *btn3;


@property(nonatomic,strong)THJDJSelectView * selectView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@end

@implementation THJDianJiaVC
-(THJDJSelectView*)selectView{
    if(!_selectView){
        _selectView = [[THJDJSelectView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _selectView.delegate = self;
    }
    return _selectView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
//    [self setStateBarColor:COLOR(83, 84, 85, 1)];
    [self setStateBarColor:SingleColor(blackColor)];
    NSLog(@"显示");
}
- (void)viewDidLoad{
    [super viewDidLoad];
    dataArr = [[NSMutableArray alloc] init];
    gongyingFlag = 1;
    send1 = @"1";//忽略
    send2 = @"sell",//sell or buy
    send3 = @"-1";//产品类别
    send4 = @"-1";//地区类别
    classType = @"1";
    [self SVHUDShow];
    socket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"wss://s.thjb.net:8185"]]];
    socket.delegate = self;
    [socket open];
    
    CGRect position;
    if(KIsiPhoneX){
         position  = CGRectMake(0, 80, ScreenWidth, ScreenHeight - 50 - 49 - 60);
    }else{
        position  = CGRectMake(0, 55, ScreenWidth, ScreenHeight - 50 - 49);
    }
    
    _tableview = [self setTableviewWithFrame:position RegisterNibNameArr:@[@"THJDianJiaCell"] ReuseIdentifierArr:@[@"cell"] RowHeight:170 BgColor:SingleColor(blackColor) IsLoadMore:NO];
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(ScreenWidth - 60, ScreenHeight - 140, 35, 35);
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(fabuBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:kGetImage(@"加号") forState:UIControlStateNormal];
    
    if(KIsiPhoneX){
        self.topSpace.constant = 45;
    }
}
/// <#Description#>
-(void)fabuBtnAction{
    if([THJTools  IsLogIn])  {
        NSLog(@"合金宝用户：%d",[THJTools isHjbUser]);
//        [self.navigationController pushViewController:[THJFabuDianjiaVC new] animated:YES];
        if([THJTools isHjbUser]){
            [self.navigationController pushViewController:[THJFabuDianjiaVC new] animated:YES];
        }else{
            [self HUDShowMsg:@"你不是合金宝用户" AfterDelayDimiss:1];
        }

    }else{
        [self.tabBarController presentViewController:[THJLoginVC new] animated:YES completion:nil];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    THJDianJiaCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSDictionary * dic = dataArr[indexPath.row];
    cell.nameLab.text = dic[@"pro_name"];
    cell.countLabel.text = [NSString stringWithFormat:@"%ld吨",[dic[@"num"] integerValue]];
    cell.priceLabel.text = [NSString stringWithFormat:@"%ld元/吨",[dic[@"price"] integerValue]];
    cell.heyueLabel.text = [NSString stringWithFormat:@"期货合约：%@",dic[@"heyue"]];
    cell.guigeLabel.text = dic[@"type_name"];
    cell.cangkuLabel.text = [NSString stringWithFormat:@"交割仓库：%@",dic[@"house"]];
    cell.addressLabel.text = [NSString stringWithFormat:@"仓库地址：%@",dic[@"address"]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if([THJTools  IsLogIn])  {
        if([THJTools isHjbUser]){
            NSDictionary * dic = dataArr[indexPath.row];
            THJDianJiaInfoVC * vc = [THJDianJiaInfoVC new];
            vc.infoDic = dic;
            vc.flag = gongyingFlag;
            NSLog(@"供应类型别-%ld",gongyingFlag);
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [self HUDShowMsg:@"你不是合金宝用户" AfterDelayDimiss:1];
        }
    }else{
        [self.tabBarController presentViewController:[THJLoginVC new] animated:YES completion:nil];
    }
    
}
//-(void)getMoRenData{
//    [THJNetWork getNetDataFromUrl:@"http://app.thjb.net/apk/dingjia.php?f=index&r=index&m=def" callback:^(NSDictionary * receiveData, NSError *error) {
//        NSLog(@"默认参数data--%@",receiveData);
//        if([receiveData[@"status"] isEqual:@"200"]){
//            [self SVHUDHiden];
//            send1 = [receiveData[@"data"][@"chang"] componentsSeparatedByString:@","][0];
//            NSLog(@"send1-%@",send1);
//            [self.btn1 setTitle:receiveData[@"data"][@"area_name"] forState:UIControlStateNormal];
//            [self.btn2 setTitle:receiveData[@"data"][@"pro_name"] forState:UIControlStateNormal];
//            [socket send:receiveData[@"data"][@"chang"]];
//        }
//    }];
//}
#pragma mark ---srsocket
- (void)webSocketDidOpen:(SRWebSocket *)webSocket{
    NSLog(@"连接成功，可以立刻登录你公司后台的服务器了，还有开启心跳");
    NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,send4];
    [socket send:sendStr];
//    [self getMoRenData];11
}
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
    NSLog(@"连接失败，这里可以实现掉线自动重连，要注意以下几点");
    NSLog(@"1.判断当前网络环境，如果断网了就不要连了，等待网络到来，在发起重连");
    NSLog(@"2.判断调用层是否需要连接，例如用户都没在聊天界面，连接上去浪费流量");
    [self SVHUDHiden];
//    NSLog(@"3.连接次数限制，如果连接失败了，重试10次左右就可以了，不然就死循环了。
//          或者每隔1，2，4，8，10，10秒重连...f(x) = f(x-1) * 2, (x=5)");
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    NSLog(@"连接断开，清空socket对象，清空该清空的东西，还有关闭心跳！");
    [self SVHUDHiden];
}
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message  {
//    NSLog(@"收到数据-%@",message);
    
    static BOOL isReceiveData = NO;
    [self SVHUDHiden];
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    dataArr = dic[@"data"];
    [_tableview reloadData];
    if([dic[@"status"] integerValue] == 200){
        [self.btn2 setTitle:dic[@"data"][0][@"pro_name"] forState:UIControlStateNormal];
    }else{
        if(!isReceiveData){
            NSLog(@"提示lable");
            [self HUDShowMsg:@"暂无数据" AfterDelayDimiss:2];
        }
        isReceiveData = YES;
    }
}
- (IBAction)areaBtnAction:(id)sender {
    self.selectView.selectIndex = 1;
    NSString * urlStr;
//    NSLog(@"gongyingFlag:%ld",gongyingFlag);
    if(gongyingFlag == 1){
        urlStr = [NSString stringWithFormat:@"https://dianjia.thjb.net/dingjia.php?f=index&r=index&m=arealist&act=%ld",gongyingFlag];
        self.selectView.areaFlag = 1;
    }else{
        urlStr = [NSString stringWithFormat:@"https://dianjia.thjb.net/dingjia.php?f=index&r=index&m=arealist&act=%ld",gongyingFlag];
        self.selectView.areaFlag = 2;
    }
    [THJNetWork getNetDataFromUrl:urlStr callback:^(NSDictionary * receiveData, NSError *error) {
        NSLog(@"地区列表--%@",receiveData);
        if([receiveData[@"status"] isEqual:@"200"]){
            areaArr = receiveData[@"data"];
            if(areaArr.count == 0){
                [self HUDShowMsg:@"暂无数据" AfterDelayDimiss:1];
            }else{
                self.selectView.dataArr = receiveData[@"data"];
                self.selectView.listKey = @"name";
               
                self.selectView.type = @"area";
                [self.selectView.tableview reloadData];
                UIWindow * window = [UIApplication sharedApplication].keyWindow;
                [window addSubview:self.selectView];
            }
        }else{
            [self HUDShowMsg:@"暂无数据" AfterDelayDimiss:1];
        }
    }];
}
- (IBAction)classBtnAction:(id)sender {
    self.selectView.selectIndex = 3;
    self.selectView.dataArr = @[@{@"id":@"0",@"name":@"硅锰6517"},@{@"id":@"1",@"name":@"硅铁72"}];
    self.selectView.listKey = @"name";
    self.selectView.type = @"product";
    self.selectView.areaFlag = 1;
    [self.selectView.tableview reloadData];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.selectView];
    return;
}
- (IBAction)gongyingBtnAction:(id)sender {
    self.selectView.selectIndex = 3;
    self.selectView.dataArr = @[@{@"id":@"sell",@"name":@"供应"},@{@"id":@"buy",@"name":@"求购"}];
    self.selectView.listKey = @"name";
    self.selectView.type = @"mai";
    self.selectView.areaFlag = 1;
    [self.selectView.tableview reloadData];
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.selectView];
    return;
}
-(void)selectIndex:(NSString*)index Info:(NSDictionary*)info Type:(NSString *)type{
    if([type isEqual:@"area"]){
        //地区类别
        send4 = info[@"id"];
        [self.btn1 setTitle:info[@"name"] forState:UIControlStateNormal];
        NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,send4];
        [socket send:sendStr];
    }else if([type isEqual:@"mai"]){
        //买卖类别
        send2 = info[@"id"];
        NSLog(@"send2--%@",send2);
        [self.btn3 setTitle:info[@"name"] forState:UIControlStateNormal];
        NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,send4];
        NSLog(@"send2--%@",sendStr);
        [socket send:sendStr];
    }else if([type isEqual:@"product"]){
        //产品类别
        send3 = info[@"id"];
        [self.btn2 setTitle:info[@"name"] forState:UIControlStateNormal];
        NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,send4];
        [socket send:sendStr];
    }
}
//-(void)selectIndex:(NSInteger)index Info:(NSDictionary *)info{
////    NSLog(@"kkjj-%ld-%@",index,info);
//    if(index == 3){
//        gongyingFlag = [info[@"id"] integerValue];
//        if([info[@"name"] isEqual:@"供应"]){
//            [socket send:@"1,sell,-1,-1"];
//            send2 =  @"sell";
//        }else{
//            [socket send:@"1,buy,-1,-1"];
//            send2 =  @"buy";
//        }
//        [self SVHUDShow];
//        [self.btn3 setTitle:info[@"name"] forState:UIControlStateNormal];
//        [self.btn1 setTitle:@"全国" forState:UIControlStateNormal];
//    }else if(index == 2){
//        NSLog(@"类别:index:2");
//        [self SVHUDShow];
//        send3 = info[@"id"];
//        classType = info[@"id"];
//        NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,@"-1"];
//        [socket send:sendStr];
//        NSLog(@"sendStr:%@",sendStr);
//        [self.btn2 setTitle:info[@"name"] forState:UIControlStateNormal];
//        [self.btn1 setTitle:@"全国" forState:UIControlStateNormal];
//    }else{
//        [self SVHUDShow];
//        NSLog(@"地区:index:3");
//        send4 = info[@"id"];
//        NSString * sendStr = [NSString stringWithFormat:@"%@,%@,%@,%@",send1,send2,send3,send4];
//        [socket send:sendStr];
//        NSLog(@"sendStr:%@",sendStr);
//        [self.btn1 setTitle:info[@"name"] forState:UIControlStateNormal];
//    }
//}
-(void)selectProvince:(NSString *)province{
    NSLog(@"shengid-%@",province);
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    NSLog(@"开始滚动");

    [UIView animateWithDuration:2 animations:^{
        [btn setTransform:CGAffineTransformMakeScale(0, 0)];
    }];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"停止滚动");
    [UIView animateWithDuration:0.2 animations:^{
        [btn setTransform:CGAffineTransformMakeScale(1, 1)];
    }];
}
@end
